<template>
  <div 
    class="node" 
    :class="[nodeTypeClass, { 'selected': isSelected, 'dragging': isDragging }]"
    :style="nodeStyle"
    @mousedown="handleNodeMouseDown"
  >
    <!-- 缩放控制点 -->
    <!-- <div v-if="isSelected" class="resize-handle nw" @mousedown="startResize('nw', $event)"></div>
    <div v-if="isSelected" class="resize-handle ne" @mousedown="startResize('ne', $event)"></div>
    <div v-if="isSelected" class="resize-handle sw" @mousedown="startResize('sw', $event)"></div>
    <div v-if="isSelected" class="resize-handle se" @mousedown="startResize('se', $event)"></div>
    <div v-if="isSelected" class="resize-handle n" @mousedown="startResize('n', $event)"></div>
    <div v-if="isSelected" class="resize-handle s" @mousedown="startResize('s', $event)"></div>
    <div v-if="isSelected" class="resize-handle w" @mousedown="startResize('w', $event)"></div>
    <div v-if="isSelected" class="resize-handle e" @mousedown="startResize('e', $event)"></div> -->
    <div class="node-header">
      {{ getNodeTypeName }}
    </div>
    <div class="node-body">
      <!-- 输入端口 -->
      <div class="node-inputs">
        <div 
          v-for="(input, index) in node.inputs" 
          :key="index"
          class="node-port node-input"
          :class="input.type"
          @mouseup="handlePortMouseUp('input', index, $event)"
        >
        <div class="port-dot"></div>
          <span class="port-label">{{ input.name }}</span>
        </div>
      </div>
      
      <!-- 输出端口 -->
      <div class="node-outputs">
        <div 
          v-for="(output, index) in node.outputs" 
          :key="index"
          class="node-port node-output"
          :class="output.type"
          @mousedown="handlePortMouseDown('output', index, $event)"
        >
          <span class="port-label">{{ output.name }}</span>
          <div class="port-dot"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Node',
  props: {
    node: {
      type: Object,
      required: true
    },
    isSelected: {
      type: Boolean,
      default: false
    }
  },
  inject: {
    scale: {
      from: 'scale',
      default: () => 1
    },
    translateX: {
      from: 'translateX',
      default: () => 0
    },
    translateY: {
      from: 'translateY',
      default: () => 0
    }
  },
  data() {
    return {
      isDragging: false,
      dragOffsetX: 0,
      dragOffsetY: 0,
      hasMoved: false,
      sourcePortIndex: -1,
      MIN_SIZE: 50,
      // 存储端点的绝对坐标
      inputPortPositions: [],
      outputPortPositions: []
    };
  },
  computed: {
    nodeTypeClass() {
      return {
        'node-flow': this.node.type === 'flow',
        'node-procedure': this.node.type === 'procedure',
        'node-product': this.node.type === 'product'
      };
    },
    nodeStyle() {
      return {
        left: `${this.node.x}px`,
        top: `${this.node.y}px`,
        width: `${this.node.width}px`,
        height: `${this.node.height}px`,
        'border-left': this.node.type === 'flow' ? '4px solid #48bb78' : 
                      this.node.type === 'procedure' ? '4px solid #4299e1' : 
                      '4px solid #9f7aea'
      };
    },
    getNodeTypeName() {
      return this.node.type === 'product' ? '产品节点' : 
             this.node.type === 'flow' ? '流程节点' : '过程节点';
    }
  },
  mounted() {
    // 在组件挂载后计算端点坐标
    this.updatePortPositions();
  },
  watch: {
    // 监听节点位置变化，更新端点坐标
    'node.x': function() {
      this.updatePortPositions();
    },
    'node.y': function() {
      this.updatePortPositions();
    },
    'node.width': function() {
      this.updatePortPositions();
    },
    'node.height': function() {
      this.updatePortPositions();
    }
  },
  methods: {
    // 计算并更新所有端点的绝对坐标
    updatePortPositions() {
      // 确保DOM已经渲染
      this.$nextTick(() => {
        // 更新输入端点坐标
        this.inputPortPositions = this.node.inputs.map((input, index) => {
          const portElement = this.$el.querySelectorAll('.node-input')[index];
          if (portElement) {
            const portRect = portElement.getBoundingClientRect();
            const editorRect = this.$parent.$el.getBoundingClientRect();
            
            // 计算端口在画布中的绝对位置（考虑缩放和平移）
            const portX = (portRect.left + portRect.width / 2 - editorRect.left - this.translateX()) / this.scale();
            const portY = (portRect.top + portRect.height / 2 - editorRect.top - this.translateY()) / this.scale();
            
            return { x: portX, y: portY };
          }
          // 如果DOM元素不可用，使用相对坐标计算
          return { x: this.node.x + input.x, y: this.node.y + input.y };
        });
        
        // 更新输出端点坐标
        this.outputPortPositions = this.node.outputs.map((output, index) => {
          const portElement = this.$el.querySelectorAll('.node-output')[index];
          if (portElement) {
            const portRect = portElement.getBoundingClientRect();
            const editorRect = this.$parent.$el.getBoundingClientRect();
            
            // 计算端口在画布中的绝对位置（考虑缩放和平移）
            const portX = (portRect.left + portRect.width / 2 - editorRect.left - this.translateX()) / this.scale();
            const portY = (portRect.top + portRect.height / 2 - editorRect.top - this.translateY()) / this.scale();
            
            return { x: portX, y: portY };
          }
          // 如果DOM元素不可用，使用相对坐标计算
          return { x: this.node.x + output.x, y: this.node.y + output.y };
        });
      });
    },
    startResize(direction, e) {
      e.stopPropagation();
      this.isDragging = true;
      this.dragOffsetX = e.clientX;
      this.dragOffsetY = e.clientY;
      
      const initialWidth = this.node.width;
      const initialHeight = this.node.height;
      const initialX = this.node.x;
      const initialY = this.node.y;

      document.addEventListener('mousemove', (moveEvent) => {
        this.handleResize(moveEvent, direction, {
          initialWidth,
          initialHeight,
          initialX,
          initialY
        });
      });
      
      document.addEventListener('mouseup', () => {
        this.isDragging = false;
        document.removeEventListener('mousemove', this.handleResize);
        document.removeEventListener('mouseup', this.handleResize);
      }, { once: true });
    },
    
    handleResize(e, direction, initial) {
      if (!this.isDragging) return;
      
      const deltaX = e.clientX - initial.initialX;
      const deltaY = e.clientY - initial.initialY;
      
      let newWidth = initial.initialWidth;
      let newHeight = initial.initialHeight;
      let newX = initial.initialX;
      let newY = initial.initialY;

      switch(direction) {
        case 'e':
          newWidth = Math.max(this.MIN_SIZE, initial.initialWidth + deltaX);
          break;
        case 'w':
          newWidth = Math.max(this.MIN_SIZE, initial.initialWidth - deltaX);
          newX = initial.initialX + deltaX;
          break;
        case 's':
          newHeight = Math.max(this.MIN_SIZE, initial.initialHeight + deltaY);
          break;
        case 'n':
          newHeight = Math.max(this.MIN_SIZE, initial.initialHeight - deltaY);
          newY = initial.initialY + deltaY;
          break;
        case 'se':
          newWidth = Math.max(this.MIN_SIZE, initial.initialWidth + deltaX);
          newHeight = Math.max(this.MIN_SIZE, initial.initialHeight + deltaY);
          break;
        case 'sw':
          newWidth = Math.max(this.MIN_SIZE, initial.initialWidth - deltaX);
          newHeight = Math.max(this.MIN_SIZE, initial.initialHeight + deltaY);
          newX = initial.initialX + deltaX;
          break;
        case 'ne':
          newWidth = Math.max(this.MIN_SIZE, initial.initialWidth + deltaX);
          newHeight = Math.max(this.MIN_SIZE, initial.initialHeight - deltaY);
          newY = initial.initialY + deltaY;
          break;
        case 'nw':
          newWidth = Math.max(this.MIN_SIZE, initial.initialWidth - deltaX);
          newHeight = Math.max(this.MIN_SIZE, initial.initialHeight - deltaY);
          newX = initial.initialX + deltaX;
          newY = initial.initialY + deltaY;
          break;
      }

      this.$emit('update:size', {
        id: this.node.id,
        size: {
          width: newWidth,
          height: newHeight,
          x: newX,
          y: newY
        }
      });
    },
    handlePortMouseDown(portType, index, event) {
      if (portType === 'output') {
        this.sourcePortIndex = index;
        
        // 使用计算好的输出端点坐标
        const portPosition = this.outputPortPositions[index];
        
        // 设置拖拽源节点并通知父组件开始连线
        this.$parent.draggingSourceNode = this.node;
        this.$emit('connection-drag-start', {
          sourceNode: this.node,
          sourcePortIndex: index,
          startX: portPosition.x,
          startY: portPosition.y,
          clientX: event.clientX,
          clientY: event.clientY
        });
        
        event.stopPropagation();
      }
    },
    
    handlePortMouseUp(portType, index, event) {
      if (portType === 'input' && this.$parent.draggingSourceNode) {
        const portPosition = this.inputPortPositions[index];

        // 获取目标节点的DOM元素
        const targetPort = event.target.closest('.node-port');
        if (targetPort) {
          this.$emit('connection-created', {
            source: this.$parent.draggingSourceNode.id,
            sourcePortIndex: this.$parent.draggingSourcePortIndex,
            target: this.node.id,
            targetPortIndex: index,
            targetPortPosition: portPosition
          });
          
          // 通知父组件结束连线
          this.$emit('connection-drag-end');
        }
      }
    },
    
    handleNodeMouseDown(e) {
      if (e.target.classList.contains('node-header') || 
          e.target.classList.contains('node-body')) {
        if (!e.target.closest('.node-port')) {
          this.isDragging = e.target.classList.contains('node-header');
          this.hasMoved = false;
          this.dragOffsetX = e.clientX - this.node.x;
          this.dragOffsetY = e.clientY - this.node.y;
          if (this.isSelected) {
            this.$emit('select', null);
          }
          document.addEventListener('mousemove', this.handleDrag);
          document.addEventListener('mouseup', this.stopDrag);
        }
      }
    },
    handleDrag(e) {
      if (!this.isDragging) return;
      this.hasMoved = true;
      // 更新端点坐标
      this.updatePortPositions();
      // 发送位置更新事件，包含端点坐标
      this.$emit('update:position', {
        id: this.node.id,
        position: {
          x: e.clientX - this.dragOffsetX,
          y: e.clientY - this.dragOffsetY
        },
        portPositions: {
          inputs: this.inputPortPositions,
          outputs: this.outputPortPositions
        }
      });
    },
    stopDrag() {
      this.isDragging = false;
      document.removeEventListener('mousemove', this.handleDrag);
      document.removeEventListener('mouseup', this.stopDrag);
      
      if (!this.hasMoved) {
        this.$emit('select', this.node);
      } else if (this.isSelected) {
        this.$emit('select', this.node);
      }
      this.hasMoved = false;
    }
  }
};
</script>

<style>
@import '../assets/styles/node.css';
</style>